package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.server.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class QuanziMQService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    /**
     * 新增动态消息
     * @param publishId
     */
    public void sendSavePublishMsg(String publishId){
        sendMsg(1,publishId);
    }

    /**
     * 浏览动态消息
     * @param publishId
     */
    public void sendQueryPublishMsg(String publishId){
        sendMsg(2,publishId);
    }

    /**
     * 点赞动态消息
     * @param publishId
     */
    public void sendLikePublishMsg(String publishId){
        sendMsg(3,publishId);
    }

    /**
     * 喜欢动态消息
     * @param publishId
     */
    public void sendLovePublishMsg(String publishId){
        sendMsg(4,publishId);
    }

    /**
     * 评论动态消息
     * @param publishId
     */
    public void sendCommentPublishMsg(String publishId){
        sendMsg(5,publishId);
    }

    /**
     * 取消点赞动态消息
     * @param publishId
     */
    public void sendDisLikePublishMsg(String publishId){
        sendMsg(6,publishId);
    }

    /**
     * 取消喜欢动态消息
     * @param publishId
     */
    public void sendDisLovePublishMsg(String publishId){
        sendMsg(7,publishId);
    }

    /**
     * 发送圈子消息
     *
     * @param type      发送标记 1-发动态，2-浏览动态， 3-点赞， 4-喜欢， 5-评论，6-取消点赞，7-取消喜欢
     * @param publishId
     */
    private void sendMsg(Integer type, String publishId) {
        try {
            Long userId = UserThreadLocal.get().getId();
            Publish publish = quanZiApi.queryPublishById(publishId);
            Map<String, Object> msg = new HashMap<>();

            msg.put("type", type);
            msg.put("publishId", publishId);
            msg.put("date", System.currentTimeMillis());
            msg.put("userId", userId);
            msg.put("pid", publish.getPid());

            rocketMQTemplate.convertAndSend("tanhua-quanzi", msg);
        } catch (Exception e) {
            log.error("圈子消息发送失败 type=" + type + " ,publishId=" + publishId, e);
        }
    }
}
